<?php

require_once LIBRARIES_ENTITIES_DATABASE;
require_once LIBRARIES_ENTITIES_MENU;
require_once LIBRARIES_ENTITIES_CATEGORIES;
require_once LIBRARIES_ENTITIES_MENUTYPES;
require_once LIBRARIES_ENTITIES_ARTICLES;



require_once LIBRARIES_TOOLS_UTILITY;
require_once LIBRARIES_TOOLS_XTEMPLATE;
require_once LIBRARIES_TOOLS_PAGERBACKEND;

class MenuController {

    public function invoke() {

        $groupFunctions = $_SESSION['groupFunctions'];

        $userID = $_SESSION["session"]["sUserID"];


        $view = '';
        if (isset($_GET['view'])) {
            $view = $_GET['view'];
        }


        $action = '';
        if (isset($_POST['hdAction'])) {
            $action = $_POST['hdAction'];
        }


        $dir = dirname(__FILE__);


        $task = '';
        if (isset($_GET['task'])) {
            $task = $_GET['task'];
        }


        $rowToView = 10;
        if (isset($_POST["limit"])) {
            $rowToView = $_POST["limit"];
        }


        if ($view == 'menu') {


            switch ($action) {
                case 'publish':
                    $values = $_POST["cid"];
                    $result = $this->updateMenuStatus($values, true);
                    Utility::redirectCurrentPage();
                    break;
                case 'unpublish':
                    $values = $_POST["cid"];
                    $result = $this->updateMenuStatus($values, false);
                    Utility::redirectCurrentPage();
                    break;
                case 'orderdown':
                    $ID = $_POST["hdID"];
                    $result = $this->orderMenu($ID, 'down');
                    Utility::redirectCurrentPage();
                    break;
                case 'orderup':
                    $ID = $_POST["hdID"];
                    $result = $this->orderMenu($ID, 'up');
                    Utility::redirectCurrentPage();
                    break;
                case 'remove':
                    $values = $_POST["cid"];
                    $result = $this->deleteMenu($values);
                    if ($result == OK) {
                        Utility::messageBox('Xóa thành công');
                        Utility::redirectCurrentPage();
                    }
                    break;
                case 'add':
                case 'addAndExit':

                    $title = $_POST['txtTitle'];
                    $parentID = $_POST['slParentID'];
                    $menuType = $_POST['slMenuType'];

                    $target = $_POST['slTarget'];
                    $status = $_POST['rdoStatus'];
                    $createdDate = Utility::formatDateTime($_POST['txtCreatedDate']);
                    $categoryID = $_POST['hdCategoryID'];
                    $link = '';

                    if ($menuType == 'Album') {
                        $link = './com_gallery/' . $_POST['slImageCategory'] . '.htm';
                    } else if ($menuType == 'Bài viết') {
                        $link = './com_content/articles/' . $_POST['slArticle'] . '.htm';
                    } else if ($menuType == 'Liên hệ') {
                        $link = './com_contact/contact.htm';
                    } else if ($menuType == 'Liên kết ngoài') {
                        $link = $_POST['txtUrl'];
                    } else if ($menuType == 'Nhóm bài viết') {
                        $link = './com_content/categories/' . $_POST['slArticleCategory'] . '.htm';
                    } else if ($menuType == 'Nhóm sản phẩm') {
                        $link = './com_item/categories/' . $_POST['slItemCategory'] . '.htm';
                    } else if ($menuType == 'Tất cả Album ảnh') {
                        $link = 'com_gallery/all_album.htm';
                    }

                    $result = $this->addMenu($title, $link, $categoryID, $target, $parentID, $createdDate, $userID, $menuType, $status);

                    if ($result == OK) {
                        if ($action == 'add') {
                            Utility::messageBox('Thêm thành công');
                            Utility::redirectCurrentPage();
                        } else {
                            Utility::redirect(".?com=com_menu&view=menu&task=view&categoryID=" . $categoryID . "");
                        }
                    }
                    break;
                case 'edit':
                case 'editAndExit':

                    $ID = $_POST['hdID'];
                    $title = $_POST['txtTitle'];
                    $parentID = $_POST['slParentID'];
                    $menuType = $_POST['slMenuType'];

                    $target = $_POST['slTarget'];
                    $status = $_POST['rdoStatus'];
                    $createdDate = Utility::formatDateTime($_POST['txtCreatedDate']);
                    $categoryID = $_POST['hdCategoryID'];

                    $link = '';

                    if ($menuType == 'Album') {
                        $link = './com_gallery/' . $_POST['slImageCategory'] . '.htm';
                    } else if ($menuType == 'Bài viết') {
                        $link = './com_content/articles/' . $_POST['slArticle'] . '.htm';
                    } else if ($menuType == 'Liên hệ') {
                        $link = './com_contact/contact.htm';
                    } else if ($menuType == 'Liên kết ngoài') {
                        $link = $_POST['txtUrl'];
                    } else if ($menuType == 'Nhóm bài viết') {
                        $link = './com_content/categories/' . $_POST['slArticleCategory'] . '.htm';
                    } else if ($menuType == 'Nhóm sản phẩm') {
                        $link = './com_item/categories/' . $_POST['slItemCategory'] . '.htm';
                    } else if ($menuType == 'Tất cả Album ảnh') {
                        $link = 'com_gallery/all_album.htm';
                    }

                    $result = $this->updateMenu($ID, $title, $link, $categoryID, $target, $parentID, $createdDate, $userID, $menuType, $status);

                    if ($result == OK) {
                        if ($action == 'edit') {
                            Utility::messageBox('Cập nhật thành công');
                            Utility::redirectCurrentPage();
                        } else {
                            Utility::redirect(".?com=com_menu&view=menu&task=view&categoryID=" . $_POST['hdCategoryID'] . "");
                        }
                    }
                    break;
            }





            if ($task == 'view') {

                if (Utility::checkPermission('view', $groupFunctions, MENU_MANAGEMENT)) {

                    $viewFile = $dir . DS . 'views' . DS . 'menu' . DS . 'menu_list.html';
                    $xtemplate = new XTemplate($viewFile);

                    // category to filter
                    $categoryID = 0;
                    if (isset($_POST['slCategoryID'])) {
                        $categoryID = $_POST['slCategoryID'];
                    } else if (isset($_GET['categoryID'])) {
                        $categoryID = $_GET['categoryID'];
                    }



                    // CHECK PERMISSION
                    // check add button
                    if (Utility::checkPermission('add', $groupFunctions, MENU_MANAGEMENT)) {
                        $xtemplate->assign('SELECTED_CATEGORY_ID', $categoryID);
                        $xtemplate->parse('main.add_button');
                    }
                    // check delete button
                    if (Utility::checkPermission('delete', $groupFunctions, MENU_MANAGEMENT)) {
                        $xtemplate->parse('main.delete_button');
                    }
                    // check enable button
                    if (Utility::checkPermission('enable', $groupFunctions, MENU_MANAGEMENT)) {
                        $xtemplate->parse('main.enable_button');
                    }
                    // check disable button
                    if (Utility::checkPermission('disable', $groupFunctions, MENU_MANAGEMENT)) {
                        $xtemplate->parse('main.disable_button');
                    }




                    // index of checkbox
                    $indexCheckBox = 1;

                    // current page
                    $rurrentPage = 1;
                    if (isset($_POST["page"])) {
                        $rurrentPage = $_POST["page"];
                    }

                    // index of item
                    $index = 1;


                    $this->fillSelectBox_MenuCategory($xtemplate);

                    $menus = $this->getMenuListByCategoryID($categoryID);


                    // get pager object
                    $pager = PagerBackEnd::getPagerData(count($menus), $rowToView, $rurrentPage);

                    if ($menus != null) {
                        $indexCheckBox = 1;

                        // loop and print each item
                        foreach ($menus as $menu) {
                            if ($index > $pager->offset && $index <= $pager->limit) {

                                $xtemplate->assign('INDEX', $index);
                                $xtemplate->assign('INDEX_CHECKBOX', $indexCheckBox);
                                $xtemplate->assign('ID', $menu->getID());
                                $xtemplate->assign('TITLE', $menu->getTitle());
                                $xtemplate->assign('LINK', $menu->getLink());

                                $xtemplate->assign('CREATED_USER', $menu->getCreatedUser()->getFullname());
                                $xtemplate->assign('MODIFIED_USER', $menu->getModifiedUser()->getFullname());
                                $xtemplate->assign('CREATED_DATE', Utility::formatDateTimeToView($menu->getCreatedDate()));
                                $xtemplate->assign('MODIFIED_DATE', Utility::formatDateTimeToView($menu->getModifiedDate()));
                                $xtemplate->assign('ORDER', $menu->getOrder());


                                // target
                                switch ($menu->getTarget()) {
                                    case '_blank':
                                        $xtemplate->assign('TARGET', 'Trang mới');
                                        break;
                                    case '_self':
                                        $xtemplate->assign('TARGET', 'Trang hiện tại');
                                        break;
                                }


                                // status
                                if ($menu->getStatus() == 1) {
                                    $xtemplate->assign('STATUS_ACTION', 'unpublish');
                                    $xtemplate->assign('STATUS_IMAGE', 'publish_g.png');
                                } else {
                                    $xtemplate->assign('STATUS_ACTION', 'publish');
                                    $xtemplate->assign('STATUS_IMAGE', 'publish_r.png');
                                }



                                // check update permission                            
                                if (Utility::checkPermission('update', $groupFunctions, MENU_MANAGEMENT)) {
                                    $xtemplate->parse('main.row.update_button');
                                } else {
                                    $xtemplate->parse('main.row.update_button_disable');
                                }


                                // order
                                // if the the first order then show the down arrow
                                if ($index == 1) {
                                    $xtemplate->parse('main.row.down_arrow');
                                }
                                // if the last order the show the up arrow
                                else if ($index == count($menus)) {
                                    $xtemplate->parse('main.row.up_arrow');
                                }
                                // else show both arrow
                                else {

                                    $xtemplate->parse('main.row.up_down_arrow');
                                }



                                $xtemplate->parse('main.row');

                                $indexCheckBox++;
                            }
                            $index++;
                        }
                    }

                    // limit list
                    $xtemplate->assign('LIMIT_LIST', Utility::getLimitList($rowToView));

                    // show amount of row to view
                    $xtemplate->assign('ROW_TO_VIEW', $rowToView);

                    // show current page
                    $xtemplate->assign('CURRENT_PAGE', $rurrentPage);

                    // amount of item
                    $xtemplate->assign('AMOUNT_OF_ITEM', $pager->numPages);

                    // paging html
                    $xtemplate->assign('PAGING_HTML', $pager->paging);


                    $xtemplate->parse('main');
                    $xtemplate->out('main');
                } else {
                    echo ERROR_PERMISSION;
                }
            } else if ($task == 'add') {

                if (Utility::checkPermission('add', $groupFunctions, MENU_MANAGEMENT)) {
                    $xtemplate = new XTemplate($dir . DS . 'views' . DS . 'menu' . DS . 'menu_add.html');

                    $categoryID = 0;
                    if (isset($_POST['slCategoryID'])) {
                        $categoryID = $_POST['slCategoryID'];
                    } else if (isset($_GET['categoryID'])) {
                        $categoryID = $_GET['categoryID'];
                    }

                    $this->fillSelectBox_Target($xtemplate);
                    $this->fillSelectBox_MenuCategory($xtemplate, $categoryID);
                    $this->fillSelectBox_MenuByCategoryID($xtemplate, $categoryID);
                    $this->fillSelectBox_MenuType($xtemplate);

                    $this->fillSelectBox_ArticleCategory($xtemplate);
                    $this->fillSelectBox_ItemCategory($xtemplate);
                    $this->fillSelectBox_ImageCategory($xtemplate);
                    $this->fillSelectBox_Article($xtemplate);


                    $xtemplate->assign('CATEGORY_ID', $categoryID);
                    $xtemplate->assign('TODAY', date('d/m/Y'));
                    $xtemplate->assign('UPLOAD_FOLDER', UPLOAD_FOLDER);
                    $xtemplate->parse('main');
                    $xtemplate->out('main');
                } else {
                    echo ERROR_PERMISSION;
                }
            }
            // edit task
            else if ($task == 'edit') {

                if (Utility::checkPermission('update', $groupFunctions, MENU_MANAGEMENT)) {


                    $ID = $_GET['ID'];
                    $menu = $this->getMenuByID($ID);




                    if ($menu != null) {

                        $xtemplate = new XTemplate($dir . DS . 'views' . DS . 'menu' . DS . 'menu_edit.html');

                        $this->fillSelectBox_Target($xtemplate, $menu->getTarget());
                        $this->fillSelectBox_MenuType($xtemplate, $menu->getMenuType());
                        $this->fillSelectBox_MenuCategory($xtemplate, $menu->getCategoryID());
                        $this->fillSelectBox_MenuByCategoryID($xtemplate, $menu->getCategoryID(), $menu->getParentID());


                        // get id from link
                        $linkID = $menu->getLink();
                        $linkArray = explode('/', $linkID);
                        $linkID = $linkArray[(int) count($linkArray) - 1];
                        $linkID = strrev($linkID);
                        $linkID = substr($linkID, (int) strpos($linkID, '.') + 1, strlen($linkID));
                        $linkID = strrev($linkID);


                        $this->fillSelectBox_ArticleCategory($xtemplate, $linkID);
                        $this->fillSelectBox_ItemCategory($xtemplate, $linkID);
                        $this->fillSelectBox_ImageCategory($xtemplate, $linkID);
                        $this->fillSelectBox_Article($xtemplate, $linkID);

                        if ($menu->getStatus() == 1) {
                            $xtemplate->parse('main.status_true');
                        } else {
                            $xtemplate->parse('main.status_false');
                        }

                        $xtemplate->assign('ID', $menu->getID());
                        $xtemplate->assign('CATEGORY_ID', $menu->getCategoryID());
                        $xtemplate->assign('PARENT_ID', $menu->getParentID());
                        $xtemplate->assign('MENUTYPE', $menu->getMenuType());
                        $xtemplate->assign('TITLE', $menu->getTitle());
                        $xtemplate->assign('MODIFIED_DATE', Utility::formatDateTimeToView($menu->getModifiedDate()));
                        $xtemplate->assign('LINK', $menu->getLink());
                        $xtemplate->parse('main');
                        $xtemplate->out('main');
                    } else {
                        echo 'Không tồn tại dữ liệu';
                    }
                } else {
                    echo ERROR_PERMISSION;
                }
            }
        }
        // view category
        else if ($view == 'category') {

            switch ($action) {
                case 'publish':
                    $values = $_POST["cid"];
                    $result = $this->updateCategoryStatus($values, true);
                    Utility::redirectCurrentPage();
                    break;
                case 'unpublish':
                    $values = $_POST["cid"];
                    $result = $this->updateCategoryStatus($values, false);
                    Utility::redirectCurrentPage();
                    break;
                case 'orderdown':
                    $categoryID = $_POST["hdCategoryID"];
                    $result = $this->orderCategory($categoryID, 'down');
                    Utility::redirectCurrentPage();
                    break;
                case 'orderup':
                    $categoryID = $_POST["hdCategoryID"];
                    $result = $this->orderCategory($categoryID, 'up');
                    Utility::redirectCurrentPage();
                    break;
                case 'remove':
                    $values = $_POST["cid"];
                    $result = $this->deleteCategory($values);
                    if ($result == OK) {
                        Utility::messageBox('Xóa thành công');
                        Utility::redirectCurrentPage();
                    }
                    break;
                case 'add':
                case'addAndExit':
                    $title = $_POST['txtTitle'];
                    $alias = Utility::removeSigns($_POST['txtAlias']);
                    $description = Utility::replaceHtmlSpecialChars($_POST['txtDescription']);
                    $parent = 0;
                    $createdDate = Utility::formatDateTime($_POST['createdDate']);
                    $status = $_POST['rdoState'];
                    $createdUserID = $userID;

                    $result = $this->addCategory($parent, $title, $alias, $createdDate, $description, $createdUserID, $status);

                    if ($result == OK) {
                        if ($action == 'add') {
                            Utility::messageBox('Thêm thành công');
                            Utility::redirectCurrentPage();
                        } else {

                            Utility::redirect(".?com=com_menu&view=category&task=view");
                        }
                    }
                    break;
                case 'edit':
                case 'editAndExit':
                    $categoryID = $_POST['hdCategoryID'];
                    $title = $_POST['txtTitle'];
                    $alias = Utility::removeSigns($_POST['txtAlias']);
                    $description = Utility::replaceHtmlSpecialChars($_POST['txtDescription']);
                    // $parent = $_POST['parentID'];
                    $parent = 0;
                    $createdDate = Utility::formatDateTime($_POST['createdDate']);
                    $status = $_POST['rdoState'];
                    $createdUserID = $userID;

                    $result = $this->updateCategory($parent, $title, $alias, $createdDate, $description, $createdUserID, $status, $categoryID);

                    if ($result == OK) {
                        if ($action == 'edit') {
                            Utility::messageBox('Sửa thành công');
                            Utility::redirectCurrentPage();
                        } else {

                            Utility::redirect(".?com=com_menu&view=category&task=view");
                        }
                    }
                    break;
            }



            if ($task == 'view') {

                if (Utility::checkPermission('view', $groupFunctions, MENU_CATEGORY_MANAGEMENT)) {
                    $xtemplate = new XTemplate($dir . '/views/category/category_list.html');

                    // CHECK PERMISSION
                    // check add button
                    if (Utility::checkPermission('add', $groupFunctions, MENU_CATEGORY_MANAGEMENT)) {
                        $xtemplate->parse('main.add_button');
                    }
                    // check delete button
                    if (Utility::checkPermission('delete', $groupFunctions, MENU_CATEGORY_MANAGEMENT)) {
                        $xtemplate->parse('main.delete_button');
                    }
                    // check enable button
                    if (Utility::checkPermission('enable', $groupFunctions, MENU_CATEGORY_MANAGEMENT)) {
                        $xtemplate->parse('main.enable_button');
                    }
                    // check disable button
                    if (Utility::checkPermission('disable', $groupFunctions, MENU_CATEGORY_MANAGEMENT)) {
                        $xtemplate->parse('main.disable_button');
                    }

                    $categoryID = 0;
                    if (isset($_POST['slCategoryID'])) {
                        $categoryID = $_POST['slCategoryID'];
                    } else if (isset($_GET['categoryID'])) {
                        $categoryID = $_GET['categoryID'];
                    }


                    $indexCheckBox = 1;


                    $rurrentPage = 1;
                    if (isset($_POST["page"])) {
                        $rurrentPage = $_POST["page"];
                    }

                    $index = 1;

                    $categories = $this->getCategoryListByComponentID(MENU_COMPONENT);


                    $pager = PagerBackEnd::getPagerData(count($categories), $rowToView, $rurrentPage);

                    if ($categories != null) {
                        $indexCheckBox = 1;
                        for ($i = 0; $i < count($categories); $i++) {

                            if ($index > $pager->offset && $index <= $pager->limit) {

                                $xtemplate->assign('INDEX', $index);
                                $xtemplate->assign('INDEX_CHECKBOX', $indexCheckBox);
                                $xtemplate->assign('CATEGORY_ID', $categories[$i]->getID());
                                $xtemplate->assign('CATEGORY_TITLE', $categories[$i]->getTitle());
                                $xtemplate->assign('CATEGORY_ORDER', $categories[$i]->getOrder());
                                $xtemplate->assign('CREATED_USER', $categories[$i]->getCreateUser()->getFullname());
                                $xtemplate->assign('MODIFIED_USER', $categories[$i]->getModifiedUser()->getFullname());
                                $xtemplate->assign('CREATED_DATE', $categories[$i]->getCreatedDate());
                                $xtemplate->assign('MODIFIED_DATE', $categories[$i]->getModifiedDate());

                                // check update permission                            
                                if (Utility::checkPermission('update', $groupFunctions, MENU_CATEGORY_MANAGEMENT)) {
                                    $xtemplate->parse('main.category_list.update_button');
                                } else {
                                    $xtemplate->parse('main.category_list.update_button_disable');
                                }

                                // check menulist view permission                            
                                if (Utility::checkPermission('view', $groupFunctions, MENU_MANAGEMENT)) {
                                    $xtemplate->parse('main.category_list.menulist_button');
                                } else {
                                    $xtemplate->parse('main.category_list.menulist_button_disable');
                                }

                                if ($categories[$i]->getState() == 1) {
                                    $xtemplate->assign('STATUS_ACTION', 'unpublish');
                                    $xtemplate->assign('STATUS_IMAGE', 'publish_g.png');
                                } else {
                                    $xtemplate->assign('STATUS_ACTION', 'publish');
                                    $xtemplate->assign('STATUS_IMAGE', 'publish_r.png');
                                }

                                if ($index == 1) {
                                    $xtemplate->parse('main.category_list.down_arrow');
                                } else if ($index == count($categories)) {
                                    $xtemplate->parse('main.category_list.up_arrow');
                                } else {
                                    $xtemplate->parse('main.category_list.up_down_arrow');
                                }

                                $xtemplate->parse('main.category_list');

                                $indexCheckBox++;
                            }
                            $index++;
                        }



                        $xtemplate->assign('LIMIT_LIST', Utility::getLimitList($rowToView));


                        $xtemplate->assign('ROW_TO_VIEW', $rowToView);

                        $xtemplate->assign('CURRENT_PAGE', $rurrentPage);


                        $xtemplate->assign('AMOUNT_OF_PAGE', $pager->numPages);


                        $xtemplate->assign('PAGING_HTML', $pager->paging);
                    }
                    $xtemplate->parse('main');
                    $xtemplate->out('main');
                } else {
                    echo ERROR_PERMISSION;
                }
            } else if ($task == 'add') {
                if (Utility::checkPermission('add', $groupFunctions, MENU_CATEGORY_MANAGEMENT)) {
                    $xtemplate = new XTemplate($dir . '/views/category/category_add.html');

                    $this->fillSelectBox_MenuCategory($xtemplate);

                    $xtemplate->assign('TODAY', date('d/m/Y'));
                    $xtemplate->parse('main');
                    $xtemplate->out('main');
                } else {
                    echo ERROR_PERMISSION;
                }
            } else if ($task == 'edit') {
                if (Utility::checkPermission('update', $groupFunctions, MENU_CATEGORY_MANAGEMENT)) {
                    $categoryID = '';
                    if (isset($_GET['categoryID'])) {
                        $categoryID = $_GET['categoryID'];
                    }

                    $category = $this->getCategoryByID($categoryID);

                    if ($category != null) {
                        $xtemplate = new XTemplate($dir . DS . 'views' . DS . 'category' . DS . 'category_edit.html');

                        $this->fillSelectBox_MenuCategory($xtemplate, $category->getParent());

                        $xtemplate->assign('CATEGORY_MODIFIED_DATE', $category->getModifiedDate());

                        $xtemplate->assign('CATEGORY_TITLE', $category->getTitle());


                        $xtemplate->assign('CATEGORY_ALIAS', $category->getAlias());

                        $xtemplate->assign('CATEGORY_DESCRIPTION', $category->getDescription());

                        $xtemplate->assign('CATEGORY_ID', $category->getID());

                        if ($category->getState() == 1) {
                            $xtemplate->parse('main.state_true');
                        } else {
                            $xtemplate->parse('main.state_false');
                        }
                        $xtemplate->parse('main');
                        $xtemplate->out('main');
                    } else {
                        Utility::redirect('.?com = com_menu&view = category&task = view');
                    }
                } else {
                    echo ERROR_PERMISSION;
                }
            }
        } else {
            Utility::redirect('.');
        }
    }

    private function getMenuListByCategoryID($categoryID, $parentID = 0, $space = '', $rows = null) {
        $db = new Database();
        try {
            if (!$rows) {
                $rows = array();
            }

            $menu = new Menu();
            $menu->setCategoryID($categoryID); // mã thành phần sản phẩm
            $menu->setParentID($parentID);
            $result = $menu->getListByParentIDAndCategoryID($db);
            $db->submitChanges();

            if ($result != null) {
                for ($i = 0; $i < count($result); $i++) {
                    $result[$i]->setTitle($space . $result[$i]->getTitle());
                    $rows[] = $result[$i];
                    $rows = $this->getMenuListByCategoryID($categoryID, $result[$i]->getID(), $space . '|__&nbsp;', $rows);
                }
            }
            return $rows;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function fillSelectBox_MenuByCategoryID($xtemplate, $categoryID, $selectedID = null) {

        $menus = $this->getMenuListByCategoryID($categoryID);
        if (count($menus) > 0) {
            foreach ($menus as $menu) {
                $xtemplate->assign('MENU_ID', $menu->getID());
                $xtemplate->assign('MENU_TITLE', $menu->getTitle());
                if ($selectedID != null) {
                    if ($selectedID == $menu->getID()) {
                        $xtemplate->assign('SELECTED', 'selected');
                    } else {
                        $xtemplate->assign('SELECTED', '');
                    }
                }
                $xtemplate->parse('main.menu_list');
            }
        }
    }

    private function fillSelectBox_MenuType($xtemplate, $selectedID = null) {

        $db = new Database();
        try {
            $menuType = new MenuTypes();
            $menuTypes = $menuType->getList($db);

            if (count($menuTypes) > 0) {
                foreach ($menuTypes as $row) {

                    if ($selectedID != null) {
                        if ($selectedID == $row->getName()) {
                            $xtemplate->assign('SELECTED', 'selected');
                        } else {
                            $xtemplate->assign('SELECTED', '');
                        }
                    }
                    $xtemplate->assign('MENU_TYPE', $row->getName());
                    $xtemplate->parse('main.menu_type_list');
                }
            }
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function addMenu($title, $link, $categoryID, $target, $parentID, $createdDate, $createdUserID, $menuType, $status) {
        $db = new Database();
        try {

            $parentMenu = new Menu();
            $parentMenu->setID($parentID);
            $parentMenu = $parentMenu->getByID($db);

            $menu = new Menu();
            $menu->setTitle($title);
            $menu->setLink($link);
            $menu->setCategoryID($categoryID);
            $menu->setTarget($target);
            $menu->setParentID($parentID);
            $menu->setCreatedDate($createdDate);
            $menu->setModifiedDate($createdDate);
            $menu->setStatus($status);
            $menu->setOrder($menu->getMaxOrderByParentID($db));

            if ($parentMenu != null) {
                $menu->setLevel((int) $parentMenu->getLevel() + 1);
            } else {
                $menu->setLevel(0);
            }

            $menu->setCreatedUserID($createdUserID);
            $menu->setModifiedUserID($createdUserID);
            $menu->setMenuType($menuType);


            $menu->add($db);

            $db->submitChanges();

            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            return false;
        }
    }

    private function updateMenu($ID, $title, $link, $categoryID, $target, $parentID, $createdDate, $createdUserID, $menuType, $status) {
        $db = new Database();
        try {


            $parentMenu = new Menu();
            $parentMenu->setID($parentID);
            $parentMenu = $parentMenu->getByID($db);

            $menu = new Menu();

            $menu->setID($ID);

            $menu->setTitle($title);
            $menu->setLink($link);
            $menu->setCategoryID($categoryID);
            $menu->setTarget($target);
            $menu->setParentID($parentID);
            $menu->setModifiedDate($createdDate);
            $menu->setStatus($status);
            $menu->setOrder($menu->getMaxOrderByParentID($db));

            if ($parentMenu != null) {
                $menu->setLevel((int) $parentMenu->getLevel() + 1);
            } else {
                $menu->setLevel(0);
            }

            $menu->setModifiedUserID($createdUserID);

            $menu->setMenuType($menuType);


            $menu->update($db);

            $db->submitChanges();

            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            return false;
        }
    }

    // get detail of an item
    private function getMenuByID($ID) {
        $db = new Database();
        try {
            $menu = new Menu();
            $menu->setID($ID);
            $result = $menu->getByID($db);

            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            return null;
        }
    }

    // hàm cập nhật highlight bài viết
    private function deleteMenu($values) {
        $db = new Database();
        try {
            for ($i = 0; $i < count($values); $i++) {
                $menu = new Menu();
                $menu->setID($values[$i]);
                $menu->delete($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    // hàm cập nhật trạng thái bài viết
    private function updateMenuStatus($values, $status) {
        $db = new Database();
        try {
            for ($i = 0; $i < count($values); $i++) {
                $menu = new Menu();
                $menu->setID($values[$i]);
                if ($status == true) {
                    $menu->setStatus(1);
                } else {
                    $menu->setStatus(0);
                }
                $menu->updateStatus($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    // order item
    private function orderMenu($ID, $action) {
        $db = new Database();
        try {
            $menu = new Menu();
            $menu->setID($ID);
            $currentMenu = $menu->getByID($db);
            $menu->setParentID($currentMenu->getParentID());
            $menu->setLevel($currentMenu->getLevel());

            if ($action == 'up') {
                $menu->orderUp($db);
            } else {
                $menu->orderDown($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function getCategoryListByComponentID($componentID, $parentID = 0, $space = '&nbsp;
&nbsp;
', $rows = null) {
        $db = new Database();
        try {
            if (!$rows) {
                $rows = array();
            }

            $category = new Categories();
            $category->setComponentID($componentID); // mã thành phần bài viết
            $category->setParent($parentID);
            $result = $category->getListByParentIDAndComponentID($db);
            $db->submitChanges();

            if ($result != null) {
                for ($i = 0; $i < count($result); $i++) {
                    $result[$i]->setTitle($space . $result[$i]->getTitle());
                    $rows[] = $result[$i];

                    $rows = $this->getCategoryListByComponentID($componentID, $result[$i]->getID(), $space . '_|__&nbsp;
', $rows);
                }
            }
            return $rows;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->submitChanges();
            exit();
        }
    }

    private function getArticleList() {
        $db = new Database();
        try {
            $article = new Articles();
            $result = $article->getList($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function fillSelectBox_Target($xtemplate, $selectedID = null) {
        $targets = array(
            array('_self', 'Hiển thị trong cửa sổ đang xem'),
            array('_blank', 'Hiển thị trong cửa sổ mới')
        );


        for ($i = 0; $i < count($targets); $i++) {
            if ($selectedID != null) {
                if ($selectedID == $targets[$i][0]) {
                    $xtemplate->assign('SELECTED', 'selected');
                } else {
                    $xtemplate->assign('SELECTED', '');
                }
            } else {
                if ($i == 0) {
                    $xtemplate->assign('SELECTED', 'selected');
                } else {
                    $xtemplate->assign('SELECTED', '');
                }
            }

            $xtemplate->assign('TARGET_ID', $targets[$i][0]);
            $xtemplate->assign('TARGET_TITLE', $targets[$i][1]);
            $xtemplate->parse('main.target_list');
        }
    }

    private function fillSelectBox_Article($xtemplate, $selectedID = null) {

        $articles = $this->getArticleList();

        // in ra danh sách chủ đề bài viết
        foreach ($articles as $article) {

            $xtemplate->assign('ARTICLE_ID', $article->getID());
            $xtemplate->assign('ARTICLE_TITLE', $article->getTitle());
            $xtemplate->assign('ARTICLE_ALIAS', $article->getAlias());


            // nếu có tham số parentID truyền vào
            if ($selectedID != null) {
                // nếu có biến get categoryID 
                // (tức là từ form thêm hay form edit trả về)
                if ($selectedID == $article->getID()) {
                    $xtemplate->assign('SELECTED', 'selected');
                } else {
                    $xtemplate->assign('SELECTED', '');
                }
            }
            $xtemplate->parse('main.article_list');
        }
    }

    private function fillSelectBox_ArticleCategory($xtemplate, $selectedID = null) {

        // tải danh sách nhóm tin
        $categories = $this->getCategoryListByComponentID(ARTICLE_COMPONENT);

        // in ra danh sách chủ đề bài viết
        foreach ($categories as $category) {

            $xtemplate->assign('ARTICLE_CATEGORY_ID', $category->getID());
            $xtemplate->assign('ARTICLE_CATEGORY_TITLE', $category->getTitle());
            $xtemplate->assign('ARTICLE_CATEGORY_ALIAS', $category->getAlias());

            // nếu có tham số parentID truyền vào
            if ($selectedID != null) {
                // nếu có biến get categoryID 
                // (tức là từ form thêm hay form edit trả về)
                if ($selectedID == $category->getID()) {
                    $xtemplate->assign('SELECTED', 'selected');
                } else {
                    $xtemplate->assign('SELECTED', '');
                }
            }
            $xtemplate->parse('main.article_category_list');
        }
    }

    private function fillSelectBox_ItemCategory($xtemplate, $selectedID = null) {

        // tải danh sách nhóm tin
        $categories = $this->getCategoryListByComponentID(ITEM_COMPONENT);

        // in ra danh sách chủ đề bài viết
        foreach ($categories as $category) {

            $xtemplate->assign('ITEM_CATEGORY_ID', $category->getID());
            $xtemplate->assign('ITEM_CATEGORY_TITLE', $category->getTitle());
            $xtemplate->assign('ITEM_CATEGORY_ALIAS', $category->getAlias());


            // nếu có tham số parentID truyền vào
            if ($selectedID != null) {
                // nếu có biến get categoryID 
                // (tức là từ form thêm hay form edit trả về)
                if ($selectedID == $category->getID()) {
                    $xtemplate->assign('SELECTED', 'selected');
                } else {
                    $xtemplate->assign('SELECTED', '');
                }
            }
            $xtemplate->parse('main.item_category_list');
        }
    }

    private function fillSelectBox_ImageCategory($xtemplate, $selectedID = null) {

        // tải danh sách nhóm tin
        $categories = $this->getCategoryListByComponentID(IMAGE_COMPONENT);

        // in ra danh sách chủ đề bài viết
        foreach ($categories as $category) {

            $xtemplate->assign('IMAGE_CATEGORY_ID', $category->getID());
            $xtemplate->assign('IMAGE_CATEGORY_TITLE', $category->getTitle());
            $xtemplate->assign('IMAGE_CATEGORY_ALIAS', $category->getAlias());


            // nếu có tham số parentID truyền vào
            if ($selectedID != null) {
                // nếu có biến get categoryID 
                // (tức là từ form thêm hay form edit trả về)
                if ($selectedID == $category->getID()) {
                    $xtemplate->assign('SELECTED', 'selected');
                } else {
                    $xtemplate->assign('SELECTED', '');
                }
            }
            $xtemplate->parse('main.image_category_list');
        }
    }

    // show category list
    private function fillSelectBox_MenuCategory($xtemplate, $selectedID = null) {

        $categories = $this->getCategoryListByComponentID(MENU_COMPONENT);

        foreach ($categories as $category) {

            $xtemplate->assign('CATEGORY_ID', $category->getID());
            $xtemplate->assign('CATEGORY_TITLE', $category->getTitle());


            if ($selectedID != null) {
                if ($selectedID == $category->getID()) {
                    $xtemplate->assign('SELECTED_CATEGORY', 'selected');
                } else {
                    $xtemplate->assign('SELECTED_CATEGORY', '');
                }
            } else {
                if (isset($_POST['slCategoryID'])) {

                    if ($_POST['slCategoryID'] == $category->getID()) {
                        $xtemplate->assign('SELECTED_CATEGORY', 'selected');
                    } else {
                        $xtemplate->assign('SELECTED_CATEGORY', '');
                    }
                } else if (isset($_GET['categoryID'])) {

                    if ($_GET['categoryID'] == $category->getID()) {
                        $xtemplate->assign('SELECTED_CATEGORY', 'selected');
                    } else {
                        $xtemplate->assign('SELECTED_CATEGORY', '');
                    }
                } else {
                    $xtemplate->assign('SELECTED_CATEGORY', '');
                }
            }
            $xtemplate->parse('main.category_list');
        }
    }

    // update category status
    private function updateCategoryStatus($values, $status) {

        try {
            $db = new Database();
            for ($i = 0; $i < count($values); $i++) {
                $category = new Categories();
                $category->setID($values[$i]);
                if ($status == true) {
                    $category->setState(1);
                } else {
                    $category->setState(0);
                }
                $category->updateState($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            exit();
        }
    }

    // hàm tải chi tiết 1 category
    private function getCategoryByID($categoryID) {
        try {
            $db = new Database();
            $category = new Categories();
            $category->setID($categoryID);
            $category = $category->getByID($db);
            $db->submitChanges();
            return $category;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            exit();
        }
    }

    // delete a category
    private function deleteCategory($values) {
        try {
            $db = new Database();
            for ($i = 0; $i < count($values); $i++) {
                $category = new Categories();
                $category->setID($values[$i]);
                $category->delete($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            exit();
        }
    }

    // order category
    private function orderCategory($categoryID, $action) {
        $db = new Database();
        try {

            $category = new Categories();
            $category->setID($categoryID);
            $categoryLevel = $category->getByID($db);
            $category->setComponentID(MENU_COMPONENT);
            $category->setLevel($categoryLevel->getLevel());

            if ($action == 'up') {
                $category->orderUp($db);
            } else {
                $category->orderDown($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    // hàm thêm 1 bài viết
    private function addCategory($parent, $title, $alias, $createdDate, $description, $createdUserID, $status) {
        $db = new Database();
        try {

            $category = new Categories();

            // id cha
            $category->setParent($parent);

            // tieu de
            $category->setTitle($title);
            // alias
            $category->setAlias($alias);

            // ngay tao
            $category->setCreatedDate($createdDate);
            // ngay cap nhat
            $category->setModifiedDate($createdDate);

            // nguoi tao
            $category->setCreatedUserID($createdUserID);
            // nguoi cap nhat
            $category->setModifiedUserID($createdUserID);

            // mo ta
            $category->setDescription($description);
            // trang thai
            $category->setState($status);


            // cap bac
            $category->setLevel($category->getNextLevelByParentID($db));

            // ma thanh phan
            $category->setComponentID(MENU_COMPONENT);
            //
            // thu tu
            $category->setOrder($category->getMaxOrder($db));

            // them category
            $result = $category->add($db);

            $db->submitChanges();
            if ($result > 0) {
                return OK;
            } else {
                
            }
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    // hàm cập nhật 1 bài viết
    private function updateCategory($parent, $title, $alias, $createdDate, $description, $createdUserID, $status, $ID) {
        $db = new Database();
        try {

            $category = new Categories();

            // id cha
            $category->setID($ID);

            // id cha
            $category->setParent($parent);

            // tieu de
            $category->setTitle($title);

            // alias
            $category->setAlias($alias);

            // ngay cap nhat
            $category->setModifiedDate($createdDate);

            // nguoi cap nhat
            $category->setModifiedUserID($createdUserID);

            // mo ta
            $category->setDescription($description);

            // trang thai
            $category->setState($status);


            // cap bac
            $category->setLevel($category->getNextLevelByParentID($db));


            // update category
            $category->update($db);

            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

}

?>
